﻿using System;
using ECM7.NantContrib.Types;
using Microsoft.Web.Administration;
using NAnt.Core;
using NAnt.Core.Attributes;

namespace ECM7.NantContrib.Tasks.IIS7
{
	[TaskName("createIISWebSite")]
	public class CreateIISWebsiteTask : BaseTask
	{
		public CreateIISWebsiteTask()
		{
			Bindings = new IisBindingElementCollection();
		}

		[BuildElementCollection("bindings", "add", ElementType = typeof(IisBindingElement), Required = true)]
		public IisBindingElementCollection Bindings { get; set; }

		[TaskAttribute("errorIfAlreadyExists", Required = false), BooleanValidator]
		public bool ErrorIfAlreadyExists { get; set; }

		[TaskAttribute("server", Required = false)]
		[StringValidator(AllowEmpty = false)]
		public string Server { get; set; }

		[TaskAttribute("websiteName", Required = true)]
		[StringValidator(AllowEmpty = false)]
		public string WebsiteName { get; set; }

		[TaskAttribute("fileSystemPath", Required = true)]
		[StringValidator(AllowEmpty = true)]
		public string FileSystemPath { get; set; }

		[TaskAttribute("appPool", Required = true)]
		[StringValidator(AllowEmpty = false)]
		public string AppPool { get; set; }

		/// <summary>
		/// Creates website
		/// </summary>
		protected override void ExecuteTask()
		{
			try
			{
				CreateWebsite();
			}
			catch (Exception ex)
			{
				LogError("Website [{0}] not created, because an exception occurred [{1}]", WebsiteName, ex);
				throw new BuildException("Unable to create website", ex);
			}
		}

		/// <summary>
		/// Create an IIS website.
		/// </summary>
		/// <returns>Website id</returns>
		public void CreateWebsite()
		{
			//Debugger.Launch();
			if (string.IsNullOrEmpty(AppPool)) { throw new Exception("Property [AppPool] can't be null or empty"); }
			if (string.IsNullOrEmpty(WebsiteName)) { throw new Exception("Parameter [WebsiteName] can't be null or empty"); }
			if (string.IsNullOrEmpty(FileSystemPath)) { throw new Exception("Parameter [FileSystemPath] can't be null or empty"); }
			if (Bindings == null || Bindings.Count == 0) { throw new Exception("Parameter [Bindings] can't be empty"); }

			string server = string.IsNullOrWhiteSpace(Server) ? "localhost" : Server.Trim();

			using (ServerManager serverMgr = ServerManager.OpenRemote(server))
			{
				// проверки
				if (serverMgr.ApplicationPools[AppPool] == null)
				{
					throw new Exception(string.Format("Application pool [{0}] is not exists", AppPool));
				}

				if (serverMgr.Sites[WebsiteName] == null)
				{
					// добавляем сайт
					Site mySite = serverMgr.Sites.Add(WebsiteName, Bindings[0].GetProtocol(), Bindings[0].GetBindingInfo(), FileSystemPath);

					//serverMgr.ApplicationPools.Add("MyAppPool");
					mySite.ApplicationDefaults.ApplicationPoolName = AppPool;
					mySite.ServerAutoStart = true;

					for (int i = 1; i < Bindings.Count; i++)
					{
						mySite.Bindings.Add(Bindings[i].GetBindingInfo(), Bindings[i].GetProtocol());
					}

					//mySite.TraceFailedRequestsLogging.Enabled = true;
					//mySite.TraceFailedRequestsLogging.Directory = "C:\\inetpub\\customfolder\\site";

					serverMgr.CommitChanges();
					LogMessage("Website [{0}] created", WebsiteName);
				}
				else
				{
					if (!ErrorIfAlreadyExists)
					{
						LogMessage("Website [{0}] already exists", WebsiteName);
					}
					else
					{
						throw new Exception(string.Format("Website [{0}] already exists", WebsiteName));
					}
				}
			}
		}
	}
}
